<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/5/24 下午5:55
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/5/24 下午5:55
 * @FilePath: G:/chain-link-api-front/src/views/forgetPW\index.vue
 * @Description: 忘记密码
-->
<template>
  <div class="container block forget">
    <!--    左侧表单 start -->
    <div class="box left-box forget-form">
      <!-- Logo -->
      <TopLogo></TopLogo>
      <!--        表单 statr -->
      <div class="main">
        <div class="login-title">
          {{ t('global.ForgetPWD') }}
        </div>

        <el-form :model="ruleForm" ref="ruleRef" label-width="auto" :rules="rules" label-position="top">
          <el-form-item :label="t('global.Email')" prop="email" style="width: 100%">
            <el-input v-model.trim="ruleForm.email" type="text" :placeholder="t('message.PleaseInputEmail')"/>
          </el-form-item>
          <el-form-item :label="t('global.Code')" prop="code" style="width: 100%">
            <el-input v-model.trim="ruleForm.code" :placeholder="t('message.PleaseInputCode')" type="text">
              <template #suffix>
                <el-button type="primary"  link @click="getCode" :disabled="countdown.value">{{countdownText }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item :label="t('global.PassWord')" prop="password1" style="width: 100%">
            <el-input v-model.trim="ruleForm.password1" type="password" show-password :placeholder="t('message.PleaseInputPWD')"/>
          </el-form-item>
          <el-form-item :label="t('global.ConfirmPassWord')" prop="password2" style="width: 100%">
            <el-input v-model.trim="ruleForm.password2" type="password" show-password :placeholder="t('message.ConfirmPWD')"/>
          </el-form-item>
          <el-form-item class="btn" style="width:100%;margin-top:.5rem">
            <el-button type="primary" size="large" style="width: 100%" @click="handleResetPassWord">{{t('global.UpdatePassWord') }}</el-button>
          </el-form-item>
        </el-form>
      </div>

      <login-footer :footerType="'forget'"></login-footer>
    </div>

    <RightImg></RightImg>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
import { useUserStore } from "@/stores";
import TopLogo from '@/components/LoginCom/TopLogo.vue';
import LoginFooter from "@/components/LoginCom/loginFooter.vue";
import RightImg from '@/components/LoginCom/RightImg.vue';
import { getEmailCode, login, resetPassword, } from '@/require/api.js'

import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const userStore = useUserStore();
const footerType = ref('forget')

// 在组件被挂载后执行
onMounted(() => {
  resetForm()
});
const inpType1 = ref('password');
const inpType2 = ref('password');
const countdownText = ref(t('global.GetCode'))
const countdown = ref(0);
const ruleRef = ref(null)
const eye1 = ref(true)
const eye2 = ref(true)

// 获取验证码
async function getCode() {
  // 验证邮箱格式是否正确
  ruleRef.value.validateField('email', async ( valid ) => {
    if (!valid) {
      ElMessage.error(t("message.CheckEmail"));
      return false;
    }
    countdown.value = 60;
    countdownText.value = t('global.ReSend') + countdown.value + 's)';
    const intervalId = setInterval(() => {
      countdown.value--;
      countdownText.value = t('global.ReSend') + countdown.value + 's)';
      if (countdown.value <= 0) {
        clearInterval(intervalId);
        countdown.value = 60;
        countdownText.value = t('global.GetCode');
      }
    }, 1000);
    if (ruleForm.email) {
      const { code, data, msg } = await getEmailCode({ email: ruleForm.email });
      ElMessage.success(t('message.GetCodeSuccess'))
    }
  });
}

// 修改密码
async function handleResetPassWord() {
  ruleRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error(t('message.CheckInput'))
      return false;
    } else {
      const { code, data, msg } = await resetPassword({
        email: ruleForm.email,
        code: ruleForm.code,
        password: ruleForm.password1
      })

      if (code === 200) {
        ElMessage.success(t('message.ResetPWDSuccess'))
        resetForm()
        router.push({ name: 'login' })
      } else {
        ElMessage.error(msg)
      }
    }
  })
}

function resetForm() {
  ruleForm.email = ''
  ruleForm.code = ''
  ruleForm.password1 = ''
  ruleForm.password1 = ''
}

const ruleForm = reactive({
  email: '',
  code: '',
  password1: '',
  password2: '',
})
const checkPass1 = () => {
  eye1.value = !eye1.value;
  inpType1.value = inpType1.value === 'password' ? 'text' : 'password';
}
const checkPass2 = () => {
  eye2.value = !eye2.value;
  inpType2.value = inpType2.value === 'password' ? 'text' : 'password';
}

// 表单验证规则
const rules = reactive({
  email: [
    { required: true, message: t('message.EmailIsNull'), trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: t('message.PleaseInputRightEmail'), trigger: 'blur' }
  ],
  code: [
    { required: true, message: t('message.CodeIsNull'), trigger: 'blur' },
  ],
  password1: [
    { required: true, message: t('message.PWDIsNull'), trigger: 'blur' },
    { min: 8, max: 16, message: t('message.PWDLength'), trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,16}$/,
      message: t('message.PWDAa09'), trigger: 'blur'
    }
  ],
  password2: [
    { required: true, message: t('message.ConfirmPWDIsNull'), trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error(t('message.ConfirmPWDIsNull')));
        } else if (value !== ruleForm.password1) {
          callback(new Error(t('message.PWDDiff')));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
})

</script>

<style scoped lang="less">
//element plus样式 start
.el-form {

  :deep(.el-select__wrapper) {
    height: .42rem;
    border-radius: 8px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
  }

  :deep(.el-input) {
    height: .42rem;
  }

  .btn {
    :deep(.el-button) {
      //background-color: #05aa69;
      //border-color: #05aa69;
      border-radius: 8px;
      width: 3rem;
      height: .42rem;
      //color: #fff;
    }
  }
}

.example-showcase .el-dropdown+.el-dropdown {
  margin-left: 15px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

//element plus样式 end

/****** 底部“简体中文按钮” ******/
.simpleChinese.is-text:not(.is-disabled):focus-visible {
  outline: none;
}
</style>